<template>
  <t-form
    ref="form"
    :class="['item-container', `login-${type}`]"
    :data="formData"
    :rules="FORM_RULES"
    label-width="0"
    @submit="onSubmit"
  >
    <template v-if="type == 'password'">
      <t-form-item name="username">
        <t-input
          v-model="formData.username"
          size="large"
          placeholder="请输入证件号码："
        >
          <template #prefix-icon>
            <t-icon name="user" style="color: #ad2121" />
          </template>
        </t-input>
      </t-form-item>

      <t-form-item name="password" tips="初始密码为证件号码后六位">
        <t-input
          v-model="formData.password"
          size="large"
          :type="showPsw ? 'text' : 'password'"
          clearable
          placeholder="请输入密码："
        >
          <template #prefix-icon>
            <t-icon name="lock-on" style="color: #ad2121" />
          </template>
          <template #suffix-icon>
            <t-icon
              :name="showPsw ? 'browse' : 'browse-off'"
              @click="showPsw = !showPsw"
            />
          </template>
        </t-input>
      </t-form-item>
      <!-- <t-form-item
        prop="smsCaptcha"
        name="smsCaptcha"
        style="width: 60%; display: inline-block"
      >
        <t-input
          v-model="formData.smsCaptcha"
          placeholder="请输入验证码"
          type="text"
        />
      </t-form-item>
      <img :src="imgUrl" class="rand_img" @click="handleImg" />

      <div class="check-container remember-pwd">
        <t-checkbox>记住账号</t-checkbox>
        <span class="tip">忘记账号？</span>
      </div> -->
    </template>

    <!-- 扫码登陆 -->
    <!-- <template v-else-if="type == 'qrcode'">
      <div class="tip-container">
        <span class="tip">请使用微信扫一扫登录</span>
        <span class="refresh">刷新 <t-icon name="refresh" /> </span>
      </div>
      <qrcode-vue value="" :size="160" level="H" />
    </template> -->

    <!-- 手机号登陆 -->
    <!-- <template v-else>
      <t-form-item name="phone">
        <t-input
          v-model="formData.phone"
          size="large"
          placeholder="请输入手机号码"
        >
          <template #prefix-icon>
            <t-icon name="mobile" />
          </template>
        </t-input>
      </t-form-item>

      <t-form-item class="verification-code" name="verifyCode">
        <t-input
          v-model="formData.verifyCode"
          size="large"
          placeholder="请输入验证码"
        />
        <t-button
          size="large"
          variant="outline"
          :disabled="countDown > 0"
          @click="sendCode"
        >
          {{ countDown == 0 ? "发送验证码" : `${countDown}秒后可重发` }}
        </t-button>
      </t-form-item>
    </template> -->
    <t-form-item class="btn-container">
      <t-button block size="large" type="submit"> 登录 </t-button>
    </t-form-item>

    <!--  <div class="switch-container">
      <span
        v-if="type !== 'password'"
        class="tip"
        @click="switchType('password')"
        >使用账号密码登录</span
      >
      <span v-if="type !== 'qrcode'" class="tip" @click="switchType('qrcode')"
        >使用微信扫码登录</span
      >
      <span v-if="type !== 'phone'" class="tip" @click="switchType('phone')"
        >使用手机号登录</span
      >
    </div> -->
  </t-form>
</template>

<script setup lang="ts">
import QrcodeVue from "qrcode.vue";
import type { FormInstanceFunctions, FormRule } from "tdesign-vue-next";
import { MessagePlugin } from "tdesign-vue-next";
import { ref, onMounted } from "vue";
import { useRoute, useRouter } from "vue-router";

import { useCounter } from "@/hooks";
import { useUserStore, useTabsRouterStore } from "@/store";
import { TOKEN_NAME } from "@/config/global";

const userStore = useUserStore();

const INITIAL_DATA = {
  phone: "",
  username: null,
  password: null,
  verifyCode: "",
  checked: false,
  rand: 0,
  smsCaptcha: "",
  tenantCode: "10001",
};

const FORM_RULES: Record<string, FormRule[]> = {
  phone: [{ required: true, message: "手机号必填", type: "error" }],
  username: [{ required: true, message: "账号必填", type: "error" }],
  password: [{ required: true, message: "密码必填", type: "error" }],
  verifyCode: [{ required: true, message: "验证码必填", type: "error" }],
};

const type = ref("password");

const form = ref<FormInstanceFunctions>();
const formData = ref({ ...INITIAL_DATA });
const showPsw = ref(false);
formData.value.rand = Math.random();
const imgUrl = ref(
  `/api/admin/captcha/generateImageCaptcha?rand=${formData.value.rand}`
);

const [countDown, handleCounter] = useCounter();

// 切换验证码
const handleImg = () => {
  formData.value.rand = Math.random();
  imgUrl.value = `/api/admin/captcha/generateImageCaptcha?rand=${formData.value.rand}`;
};

const switchType = (val: string) => {
  type.value = val;
};

const router = useRouter();
const route = useRoute();

onMounted(() => {
  useTabsRouterStore().initHomeRouterList();
});

/**
 * 发送验证码
 */
const sendCode = () => {
  form.value.validate({ fields: ["phone"] }).then((e) => {
    if (e === true) {
      handleCounter();
    }
  });
};

const onSubmit = async ({ validateResult }) => {
  if (validateResult === true) {
    try {
      const isSuccess = await userStore.login(formData.value);
      if (isSuccess) {
        userStore.$state.token = localStorage.getItem(TOKEN_NAME);
        MessagePlugin.success("登陆成功！");
        // const redirect = route.query.redirect as string;
        // const redirectUrl = redirect
        //   ? decodeURIComponent(redirect)
        //   : "/dashboard";
        await router.push({ name: "user" });
      } else {
        MessagePlugin.error("证件号不存在或密码错误！");
      }
    } catch (e) {
      const { response } = e;
      if (response.status === 401) {
        MessagePlugin.error(response.data.error_description);
      }
      // MessagePlugin.error(e.message);
    }
  }
};
</script>

<style lang="less" scoped>
@import url("../index.less");
</style>
